﻿using System.Collections.Generic;
using System.Xml.Linq;

namespace SchemaGen.Xsd
{
    public class SComplexElement : SEntityBase, IComplexType
    {
        private SComplexType _ComplexType;
        public SComplexType ComplexType
        {
            get
            {
                if (_ComplexType == null) _ComplexType = new SComplexType();
                return _ComplexType;
            }
        }

        public int MinOccurs { get; set; }
        public int MaxOccurs { get; set; }

        public SComplexElement(string name)
            : base(SNames.Elements.Element, name)
        {
            MinOccurs = 1;
            MaxOccurs = 1;
        }

        public SComplexElement(string name, SequenceIndicator sequenceIndicator)
            : base(SNames.Elements.Element, name)
        {
            _ComplexType = new SComplexType(sequenceIndicator);
            MinOccurs = 1;
            MaxOccurs = 1;
        }

        internal override XElement Create()
        {
            var result = base.Create();

            if (MinOccurs >= 0 && MinOccurs != 1)
                result.Add(new XAttribute("minOccurs", MinOccurs));

            if (MaxOccurs != 1)
                result.Add(new XAttribute("maxOccurs", MaxOccurs == int.MaxValue || MaxOccurs < 0 ? "unbounded" : MaxOccurs.ToString()));

            if (_ComplexType != null) result.Add(_ComplexType.Create());

            return result;
        }

        #region IComplexType

        public bool IsReadOnly { get { return false; } }
        public void Clear() { _ComplexType = null; }

        public void Add(SEntityBase child)
        {
            if (_ComplexType == null) _ComplexType = new SComplexType();
            _ComplexType.Add(child);
        }

        public bool Contains(SEntityBase item)
        {
            return _ComplexType == null ? false : _ComplexType.Contains(item);
        }

        public void CopyTo(SEntityBase[] array, int arrayIndex)
        {
            if (_ComplexType != null) _ComplexType.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return _ComplexType == null ? 0 : _ComplexType.Count; }
        }

        public bool Remove(SEntityBase item)
        {
            return _ComplexType == null ? false : _ComplexType.Remove(item);
        }

        public IEnumerator<SEntityBase> GetEnumerator()
        {
            return _ComplexType == null ? new List<SEntityBase>().GetEnumerator() : _ComplexType.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _ComplexType == null ? new List<SEntityBase>().GetEnumerator() : _ComplexType.GetEnumerator();
        }

        #endregion
    }
}
